logo

The best IT Trainig Institute In Gurgaon

Handle Alert Popup

Coding of Alert Popup
package asc;

import io.github.bonigarcia.wdm.WebDriverManager;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ALertPopUp {

public static void main(String[] args) throws InterruptedException {
		
WebDriverManager.chromedriver().setup();

ChromeDriver driver = new ChromeDriver();

driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert");

driver.manage().window().maximize();


WebElement frame1 = driver.findElement(By.id("iframeResult"));

driver.switchTo().frame(frame1);

driver.findElement(By.xpath("/html/body/button")).click();

String alertText = driver.switchTo().alert().getText();
System.out.println(alertText);

Thread.sleep(2000);

driver.switchTo().alert().accept();
//	driver.switchTo().alert().dismiss();
		
driver.switchTo().parentFrame();

System.out.println(driver.getTitle());
		
//		driver.quit();

}

}
            
code
Output
output

In Selenium, handling alert pop-ups involves switching the WebDriver's context to the alert and then performing actions such as accepting, dismissing, or retrieving the alert's text.

Key Concepts of Alert Handling in Selenium:

1. Switching to Alert:

  • To interact with an alert, you first need to switch the WebDriver's context to the alert using driver .switchTo() .alert(). This method returns an Alert object that represents the alert window.

2. Retrieving Alert Text:

  • After switching to the alert, you can retrieve the text displayed in the alert using alert() .getText(). This is often used to verify the alert's content before taking further action.

3. Accepting or Dismissing the Alert:

  • Accepting: To accept the alert (equivalent to clicking "OK"), use alert() .accept().
  • Dismissing: To dismiss the alert (equivalent to clicking "Cancel" or closing the alert), use alert() .dismiss().

Breakdown Our Code

1. Setup and Navigation:

                            
    WebDriverManager.chromedriver().setup();
    ChromeDriver driver = new ChromeDriver();
    driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert");
    driver.manage().window().maximize();
                            
                        
  • This part sets up the WebDriver, opens the specified URL, and maximizes the browser window.

2. Handling the Iframe:

                            
    WebElement frame1 = driver.findElement(By.id("iframeResult"));
    driver.switchTo().frame(frame1);
                            
                        
  • This code switches the WebDriver's context to the iframe containing the button that triggers the alert.

3. Triggering the Alert:

                            
    driver.findElement(By.xpath("/html/body/button")).click();
                            
                        
  • This finds the button inside the iframe and clicks it, which triggers the JavaScript alert.

4. Switching to and Handling the Alert:

                            
    String alertText = driver.switchTo().alert().getText();
    System.out.println(alertText);
                            
                        
  • driver .switchTo() .alert(): Switches the context to the alert.
  • getText(): Retrieves the text displayed in the alert, which is then printed to the console.
                
Thread.sleep(2000);
                
            
  • This line pauses the execution for 2 seconds, allowing time to observe the alert.
  •                 
    driver.switchTo().alert().accept();
    // driver.switchTo().alert().dismiss();
                    
                
  • accept(): Accepts the alert (clicks "OK").
  • The dismiss() method, which is commented out, would dismiss the alert (click "Cancel" or close the alert).
  • 5. Returning to the Parent Frame:

                              
      driver.switchTo().parentFrame();
                              
                          
    • This switches the context back to the parent frame after handling the alert.

    6. Printing the Page Title:

                              
      System.out.println(driver.getTitle());
                              
                          
    • This prints the title of the main document, indicating the context has returned from the iframe.

    7. Closing the Browser (Optional):

                              
      // driver.quit();
                              
                          
    • This line, if uncommented, would close the browser and end the WebDriver session.

    package asc;
    
    import io.github.bonigarcia.wdm.WebDriverManager;
    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    
    public class SendkeysInAlert {
        
    public static void main(String[] args) throws InterruptedException {
                
    WebDriverManager.chromedriver().setup();
    
    ChromeDriver driver = new ChromeDriver();
    
    driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_prompt");
    
    driver.manage().window().maximize();
    
    
    WebElement frame1 = driver.findElement(By.id("iframeResult"));
    
    driver.switchTo().frame(frame1);
    
    driver.findElement(By.xpath("/html/body/button")).click();
    Thread.sleep(2000);
    
    Alert alertOnPage = driver.switchTo().alert();
    
    alertOnPage.sendKeys("Akhil Chukkalwar");
    
    alertOnPage.accept();
    
    driver.switchTo().parentFrame();
    
    System.out.println(driver.getTitle());
                
    //	driver.quit();
        
    }
        
    }
    

    This code demonstrates how to interact with a JavaScript prompt alert in Selenium WebDriver. A prompt alert allows users to input text before accepting or dismissing the alert. Here's a breakdown of the code and explanation of the key concepts:

    1. Setup and Navigation:

                  
      WebDriverManager.chromedriver().setup();
      ChromeDriver driver = new ChromeDriver();
      driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_prompt");
      driver.manage().window().maximize();
                  
              
      WebDriverManager.chromedriver().setup();:
    • This sets up the ChromeDriver using WebDriverManager library, ensuring that the correct version of the driver is used.
    • new ChromeDriver();
              
    • This initializes the ChromeDriver instance, which is the WebDriver implementation for Google Chrome.
    • driver.get(...)
    • This navigates to the specified URL containing the prompt alert exam
    • driver.manage().window().maximize();:
    • Maximizes the browser window for better visibiland interaction.

    2. Switching to the Iframe:

                  
      WebElement frame1 = driver.findElement(By.id("iframeResult"));
      driver.switchTo().frame(frame1);
                  
              
      driver.findElement(By.id("iframeResult"))
    • Locates the iframe element by its ID.
    • 
      driver.switchTo().frame(frame1);:
    • Switches the WebDriver's context to the located iframe, enabling interaction with elements inside the frame.

    3. Triggering the Prompt Alert:

      driver.findElement(By.xpath("/html/body/button")).click(); 
    • This locates the button within the iframe using an XPath selector and clicks it, which triggers the JavaScript prompt alert.

    4. Handling the Prompt Alert:

      
      Alert alertOnPage = driver.switchTo().alert();
      alertOnPage.sendKeys("Akhil Chukkalwar");
      alertOnPage.accept();
      
      Alert alertOnPage = driver.switchTo().alert();
    • Switches the context to the alert, and Alert is an interface representing the alert box.
    • alertOnPage.sendKeys("Akhil Chukkalwar");
    • Sends the specified text ("Akhil Chukkalwar") to the prompt input field. This is specific to prompt alerts that allow user input.
    • alertOnPage.accept();
    • Accepts the alert by clicking the "OK" button. In the context of a prompt alert, this also submits the input provided.

    5. Switching Back to the Main Document:

      driver.switchTo().parentFrame();
    • This command switches the context back to the parent frame (main document) from the iframe. This is necessary if further actions are required outside the iframe.

    6. Retrieving and Printing the Page Title:

      
      System.out.println(driver.getTitle());
    • This prints the title of the current page to the console. The title retrieved here would be the title of the main document, as the context has been switched back from the iframe.

    7. Quitting the Browser (Commented Out):

      
      // driver.quit();
    • This line, when uncommented, will close the browser and terminate the WebDriver session. This is generally used to clean up and end the automation process.

    Summary

    Interacting with Prompts In Selenium, sendKeys() can be used with prompt alerts to input text. This is not applicable to simple alerts or confirmation dialogs, which only allow acceptance or dismissal.

    Switching Context Always ensure you switch to the appropriate frame or alert before interacting with elements within them, and switch back if further actions are needed outside.